package com.heima.user.service.impl;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.heima.common.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.Map;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    /**
     * 查询列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        // 1 参数检查
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        // 2 条件查询
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> lambdaQueryWrapper = new LambdaQueryWrapper();
       // QueryWrapper<ApUserRealname> objectQueryWrapper = new QueryWrapper<>();

        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(ApUserRealname::getStatus, dto.getStatus());
            //objectQueryWrapper.eq(" status",dto.getStatus());
        }

        IPage<ApUserRealname> resultPage = page(page, lambdaQueryWrapper);

        // 3 返回结果
        return new PageResponseResult(dto.getPage(), dto.getSize(),
                resultPage.getTotal(), resultPage.getRecords());
    }


    @Autowired
    ApUserMapper apUserMapper;
    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    ArticleFeign articleFeign;

    /**
     * 根据状态进行审核
     * @param dto
     * @param status 2 审核失败   9 审核成功
     * @return
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //1. 校验参数
        if (dto.getId()==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"实名认证id不能为空");
        }
        //根据实名认证的id查询实名认证的信息
        ApUserRealname apUserRealname = getById(dto.getId());
        if (apUserRealname==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证信息不存在");
        }

        //判断实名认证的状态是否为待审核（1 2 9）
        if (!AdminConstants.WAIT_AUTH.equals(apUserRealname.getStatus())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"实名认证不是待审核状态");
        }

        //根据实名认证的userId查询ApUser对象信息
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        if (apUser==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在");
        }

        if (AdminConstants.PASS_AUTH.equals(status)){
            //TODO:使用AI实名认证接口，校验实名认证信息有效性
            //1. 根据身份证正面照片  OCR  扫描出 姓名 + 身份证号


            //2. 根据  姓名  +  身份证号  调用公安部接口  判断真实性 （如果不真实状态修改2）
            //executePostReq();

            //3. 使用活体检测接口  检测LiveImage是否为真实自拍  score>85  (加果不真实状态修改2)


            //4. 使用  人证核验接口  判断活体检测照片  和  身份证上的照片是否是同一个人  score>85  (如果不是状态修改2)


        }

        //2. 修改实名认证的状态
        apUserRealname.setStatus(status);
        apUserRealname.setUpdatedTime(new Date());

        if (!StringUtils.isBlank(dto.getMsg())){
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);

        //3.如果状态为9
        if (AdminConstants.PASS_AUTH.equals(status)){
            //3.1 开通自媒体账号
            WmUser wmUser = createWmUser(apUser);
            //3.2 开通作者信息
            createApAuthor(wmUser);
        }
        apUser.setFlag((short) 1);
        apUserMapper.updateById(apUser);

        /*if (dto.getId().intValue()==5){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"演示分布式事务异常，id==5时报错");
        }*/

        return ResponseResult.okResult();
    }

    /**
     * 身份证二要素验证
     *
     * @param apicode
     * @param params
     * @param url
     * @return
     */
    private Map executePostReq(String apicode, Map<String,String> params, String url){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("apicode",apicode);
        httpHeaders.setContentType(MediaType.APPLICATION_JSON); // json
        HttpEntity<String> formEntry = new HttpEntity<>(JSON.toJSONString(params), httpHeaders); // 封装请求参数
        ResponseEntity<String> response = restTemplate.postForEntity(url, formEntry, String.class);// 发送一个post请求
        String body = response.getBody();
        Map map = JSON.parseObject(body, Map.class);
        return map;
    }


    /**
     * 4.2 创建作者信息
     * @param wmUser
     * @return
     */
    private void createApAuthor(WmUser wmUser) {
        //1. 检查是否成功调用
        ResponseResult<ApAuthor> apAuthorResult = articleFeign.findByUserId(wmUser.getApUserId());
        if (apAuthorResult.getCode()!=0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,apAuthorResult.getErrorMessage());
        }
        //2. 检查作者信息是否已经存在
        ApAuthor apAuthor = apAuthorResult.getData();
        if (apAuthor!=null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"作者信息已经存在");
        }

        //3. 添加作者信息
        apAuthor=new ApAuthor();
        apAuthor.setCreatedTime(new Date());
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(AdminConstants.AUTHOR_TYPE);//自媒体人类型
        apAuthor.setUserId(wmUser.getApUserId());//APP用户Id
        apAuthor.setWmUserId(wmUser.getId());//自媒体用户Id
        ResponseResult responseResult = articleFeign.saveApAuthor(apAuthor);
        if (responseResult.getCode()!=0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,responseResult.getErrorMessage());
        }
    }


    /**
     * 4.1 创建自媒体账户
     * @param
     * @param apUser  APP端用户
     * @return
     */
    private WmUser createWmUser(ApUser apUser) {
        //1. 查询自媒体账号是否存在（app端用户密码和自媒体密码一致）
        ResponseResult<WmUser> wmUserResult = wemediaFeign.findByName(apUser.getName());
        if (wmUserResult.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,wmUserResult.getErrorMessage());
        }
        WmUser wmUser = wmUserResult.getData();
        if (wmUser!=null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"自媒体账户信息已经存在");
        }
        wmUser=new WmUser();
        wmUser.setName(apUser.getName());
        wmUser.setSalt(apUser.getSalt());  // 盐
        wmUser.setPassword(apUser.getPassword()); // 密码
        wmUser.setPhone(apUser.getPhone());
        wmUser.setCreatedTime(new Date());
        wmUser.setType(0);
        wmUser.setApUserId(apUser.getId());
        wmUser.setStatus(AdminConstants.PASS_AUTH.intValue());

        ResponseResult<WmUser> saveResult = wemediaFeign.save(wmUser);
        if (saveResult.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,saveResult.getErrorMessage());
        }
        return saveResult.getData();
    }
}